package com.demo.java.alg;

/**
 * 给定一个正整数数组arr，把arr想象成一个直方图。 返回这个直方图如果装水，最多能装下几格水？
 */
public class Water {

    // 两边循环
    public static int calcWater1(int[] a) {
        int water = 0;
        for (int i = 1; i < a.length-1; i++) {
            int leftMax = 0;
            for (int j = 0; j < i; j++) {
                if (leftMax < a[j]) {
                    leftMax = a[j];
                }
            }
            int rightMax = 0;
            for (int j = i + 1; j < a.length; j++) {
                if (rightMax < a[j]) {
                    rightMax = a[j];
                }
            }
            water += Math.max(Math.min(leftMax, rightMax) - a[i], 0);
        }
        return water;
    }
    // 初始化数组
    public static int calcWater2(int[] a) {
        int water = 0;

        int[] LMax = new int[a.length];
        int[] RMax = new int[a.length];
        LMax[0] = a[0];
        RMax[a.length - 1] = a[a.length - 1];

        // 左边最大
        for (int i = 1; i < a.length; i++) {
            LMax[i] = Math.max(LMax[i - 1], a[i]);
        }
        // 右边最大
        for (int i = a.length - 2; i >= 2; i--) {
            RMax[i] = Math.max(RMax[i + 1], a[i]);
        }
        for (int i = 1; i < a.length - 1; i++) {
            water += Math.max(Math.min(LMax[i - 1], RMax[i + 1]) - a[i], 0);
        }
        return water;
    }
    // 双边指针
    public static int calcWater3(int[] a) {
        int water = 0;
        int lmax = a[0];
        int rmax = a[a.length - 1];
        int left = 1;
        int right = a.length - 2;

        while(left <= right) {
            if (lmax <= rmax) {
                water += Math.max(lmax - a[left], 0);
                lmax = Math.max(lmax, a[left++]);
            } else {
                water += Math.max(rmax - a[right], 0);
                rmax = Math.max(rmax, a[right--]);
            }
        }
        return water;
    }

    public static void test(int[] arr) {
        System.out.println(Water.calcWater1(arr));
        System.out.println(Water.calcWater2(arr));
        System.out.println(Water.calcWater3(arr));
    }
    public static void main(String[] args) {
        int[] arr = {9, 2, 1, 4, 7, 5, 6, 8, 3};
        test(arr);
        int[] arr1 = {4, 3, 7};
        test(arr1);
    }
}
